package com.tanhua.server.controller;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 服务消费者
 * 登录控制层
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    //controller调用UserService当前业务层逻辑   UserService中是调用服务的(tanhua-dubbo-service)
    @Autowired
    private UserService userService;

    /**
     * 保存用户对象 返回UserId
     */
    @RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    public ResponseEntity saveUser(@RequestBody Map<String,String> map){
        String mobile = map.get("mobile");//手机号码
        String password = map.get("password");//密码
        Long userId = userService.saveUser(mobile,password);
        return ResponseEntity.ok(userId);//保存成功了，没有返回内容
    }

    /**
     * 根据mobile查询user对象
     */
    @RequestMapping(value = "/findUser",method = RequestMethod.GET)
    public ResponseEntity findByMobile(String mobile){
        User user = userService.findByMobile(mobile);
        return ResponseEntity.ok(user);//查询用户返回
    }


    /**
     * 注册第一步-发送验证码
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseEntity sendValidateCode(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        userService.sendValidateCode(phone);
        return ResponseEntity.ok(null);
    }

    /**
     * 登录（自动注册）第二步---验证码校验
     */
    @RequestMapping(value = "/loginVerification",method = RequestMethod.POST)
    public ResponseEntity loginVerification(@RequestBody Map<String,String> map){
        String phone = map.get("phone");//手机号码
        String verificationCode = map.get("verificationCode");//验证码
        Map<String,Object> rsMap = userService.loginVerification(phone,verificationCode);
        /*{
            "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjI4MjkzMzYsInVzZXJfaWQiOiIxIn0.Mbzn6LzsLrkVWEbhexR3lTYDZjxqIcqW11rJxDQ6Ewk",
            "isNew": true 是否新注册用户
        }*/
        return ResponseEntity.ok(rsMap);
    }

}
